package com.handpay.zztong.hp.trans.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.HttpSFTConnector;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.SecureManager;
import com.handpay.framework.swiper.ApiSwiperFactory;
import com.handpay.framework.swiper.IBusinessSwiper;
import com.handpay.framework.swiper.ISwiperListener;
import com.handpay.framework.swiper.ic.IICSelectApplicationCallback;
import com.handpay.framework.upcard.UPXMLReqComposer;
import com.handpay.framework.upcard.UPXMLRespParser;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.framework.utils.UPConnect;
import com.handpay.zztong.hp.BalanceEnquiry;
import com.handpay.zztong.hp.CameraCardPhotoActivity;
import com.handpay.zztong.hp.PreviewActivity;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.RealNameAuthentication;
import com.handpay.zztong.hp.SwiperCardKLFActivity.BackListener;
import com.handpay.zztong.hp.TradingResults;
import com.handpay.zztong.hp.TradingResultsFailed;
import com.handpay.zztong.hp.base.activity.BaseActivity;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.Account;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.config.UPConfig;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.klf.FourElementsScreen;
import com.handpay.zztong.hp.klf.PWDScreen2;
import com.handpay.zztong.hp.klf.PWDScreen2.ClickListener;
import com.handpay.zztong.hp.klf.PWDScreen2.CloseListener;
import com.handpay.zztong.hp.klf.SwiperCardView_KLF;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.other.activity.ShowHtmlActivity;
import com.handpay.zztong.hp.paymentbill.activity.QueryBillsActivity;
import com.handpay.zztong.hp.paymentbill.activity.TransResultFailureActivity;
import com.handpay.zztong.hp.paymentbill.activity.TransResultSuccessActivity;
import com.handpay.zztong.hp.paymentbill.model.Bill;
import com.handpay.zztong.hp.protocol.AQProtocolConstant;
import com.handpay.zztong.hp.protocol.ATProtocolConstant;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.protocol.ICCardConstant;
import com.handpay.zztong.hp.swiper.SwiperUtils;
import com.handpay.zztong.hp.swiper.model.AccountTransfer;
import com.handpay.zztong.hp.swiper.model.BusinessControlSwitch;
import com.handpay.zztong.hp.swiper.model.CheckSwipeCardFourElements;
import com.handpay.zztong.hp.swiper.widget.SwiperCardBluetoothView;
import com.handpay.zztong.hp.swiper.widget.SwiperCardVoiceView;
import com.handpay.zztong.hp.trans.model.MicroBalanceQueryBean;
import com.handpay.zztong.hp.trans.model.MicroSuperFeeBean;
import com.handpay.zztong.hp.ui.ZZTShowDialog;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.handpay.zztong.hp.utils.BitmapUtil;
import com.handpay.zztong.hp.utils.Errors;
import com.handpay.zztong.hp.utils.WuXianDesUtil;
import com.intsig.ccrengine.CCREngine.ResultData;
import com.intsig.ccrengine.ISCardScanActivity;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Map;
import java.util.Vector;

import se.krka.kahlua.vm.LuaTable;

/**
 * 刷卡流程
 *
 * @author jcao
 */
public class VPOSActivity extends ZZTongActivity {
    private LinearLayout llContent = null;

    // private static byte status = -1; // 刷卡器状态

    // protected static final byte Status_WaitingSwipe = 1,//等待刷卡
    // Status_WaitingInputPwd = 2,//等待输入密码
    // Status_WaitingConfirmMoney = 3;//等待确认金额

    private static double amount;
    private static double total;
    // 转账用的账号
    private Account mTransferInAccount;
    // 记录服务器返回的terminalId用于超级转账请求
    // 一开始是记录terminalId,后来是记录刷卡器加密后的terminalId.
    private String mTerminalId = "";
    // 记录交易币种
    private final String mChannelOrderCurrency = "156";
    // 记录刷卡器加密后的币种
    private String mEncryCurrency;
    // 记录刷卡器加密后的转入账号
    private String mEncEncryAccountNum2;
    // account, plainAcount, pin, track2, encAmount, random
    private String mAccount; // 转出卡刷卡器加密
    private String mPlainAccount; // 转出卡明文
    private String mPin; // 转出卡密码刷卡器加密
    private String mTrack2;
    private String mEncAmount; // 交易金额刷卡器加密
    private String mDyKey; // 刷卡器返回的数据
    private String mDCData;
    private String mICNum;
    // private String mDesTerminalId;
    private String mexpireDate; // IC 卡有效期
    /**
     * 账户管理中转账金额key
     */
    public static final String Transfer_Amount_Key = "Transfer_Amount_Key";
    /**
     * 账户管理中选中的账户key
     */
    public static final String Transfer_To_Accounts_Key = "Transfer_To_Accounts_Key";

    private SwiperCardBluetoothView swiperCardView;

    private String HPencData;
    // 韩鑫四要素 ：是否保存过四要素
    private String status;
    // 转出卡户主的身份证号码
    private String idNum;
    // 转出卡户主的手机号
    private String mobileNum;
    // 转出卡户主的姓名
    private String userName;
    private static boolean isShowAmount = false;
    private static double amV;
    private static long mLastClickTime = 0l;
    private int selectedRate;
    private int isPublicCharge;
    private boolean isRateNull;

    private String merchantId;
    private String orderId;
    private boolean SwiperTemp = false;
    // 业务控制是否打开四要素和拍照开关
    private int iIsOpenFourElements = 0, iIsOpenNeedCamera = 1, iIsOpenCardScanCamera = 0;
    // 交易时把服务器初始返回的是否需要四要素开关和拍照开关的原始数据传回给服务器
    private int iOriginIsOpenFourElements = 0, iOriginIsOpenNeedCamera = 1, iOriginIsOpenCardScanCamera = 0;
    private int isUinPayOpenFourElements = 0;//银联转账是否需要四要素验证
    private String fileUrl = null;
    private HashMap<String, String> mBankInfoHashMap;
    public int isCardRequestCode = 33301;
    public String cardImageNumber = null;
    // 0： 使用sdk内置相机模块 1：使用自定义相机模块 主要是怕更换频繁
    private int useScanType = 1;

    private String orderNo, transSeq;
    private ZZTShowDialog mDialog;
    @Override
    public ActionBar getActivityActionBar() {
        return new ActionBar(getResources().getString(R.string.four_element_title), true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.setContentView(R.layout.activity_vpos);
        //禁止截屏
        Window window = getWindow();
        WindowManager.LayoutParams winParams = window.getAttributes();
        window.addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        super.onCreate(savedInstanceState);
        // 清除factor
        clearFactor();
        llContent = (LinearLayout) this.findViewById(R.id.llContent);

        final Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle == null) {
            goBack();
        }
        // isOpen = bundle.getInt("isOpen", 0);
        fileUrl = bundle.getString("fileUrl");
        // HPLog.e(HPLog.FDL_TAG, "VPos--Oncreate---isOpen=" + isOpen +
        // "--fileUrl=" + fileUrl);
        mAction = bundle.getByte(ACTION);
        HPLog.i("VPOSActivity", "mAction:" + mAction);
        isShowAmount = !(mAction == ZZTongActivity.Action_BalanceEnquiry || mAction == ZZTongActivity.Action_Phone || mAction == ZZTongActivity.Action_Qb || mAction == ZZTongActivity.Action_Game);

        amount = bundle.getDouble(Transfer_Amount_Key);

        HPLog.i(HPLog.SSX_TAG, "接收到的刷卡金额:" + amount);
        isRateNull = bundle.getBoolean("isRateNull");
        if (!isRateNull) {
            selectedRate = bundle.getInt("selectedRate");
            isPublicCharge = bundle.getInt("isPublicCharge");
            HPLog.e("VPOSActivity", "selectedRate----------------------------------:" + selectedRate);
        }
        total = 0d;
        if (ZZTongActivity.Action_SuperTransfer == mAction || ZZTongActivity.Action_CreditCardRepay == mAction || ZZTongActivity.Action_SuperUniTrans == mAction) {
            // 只有超级转账才需要转入卡
            mTransferInAccount = (Account) intent.getSerializableExtra(Transfer_To_Accounts_Key);
            HPLog.i(HPLog.SSX_TAG, mTransferInAccount.toString());
            refreshStatus(ISwiperListener.Status_Swipe);
            SwiperTemp = true;
            doSwipe();
        } else if (ZZTongActivity.Action_Phone == mAction || ZZTongActivity.Action_Qb == mAction || ZZTongActivity.Action_Game == mAction) {
            refreshStatus(ISwiperListener.Status_Swipe);
            SwiperTemp = true;
            doSwipe();
        } else {
            forresult = bundle.getBoolean(ForResult);
            total = amount;
            if (ZZTongActivity.Action_BalanceEnquiry == mAction) {
                refreshStatus(ISwiperListener.Status_Swipe);
                SwiperTemp = true;
                doSwipe();
            } else {
                affirmAmount();
                if (!ApiSwiperFactory.getInstance().isSupportAffirmAmount()) {
                    if (ZZTongActivity.Action_MARKET == mAction) {
                        orderNo = bundle.getString("orderNo");
                        transSeq = bundle.getString("transSeq");
                    }
                    refreshStatus(ISwiperListener.Status_Swipe);
                    SwiperTemp = true;
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        SwiperCardView_KLF.frameCount = 0;
    }

    private void affirmAmount() {
        int amountLen = UPConfig.TRANS_AMOUNT_LEN;
        doAffirmAmount(CommonUtils.formatMoneyToPos(total, amountLen));
        // 如果支持确认金额。显示确认金额界面
        if (ApiSwiperFactory.getInstance().isSupportAffirmAmount()) {
            refreshStatus(ISwiperListener.Status_AffirmAmount);
        }
    }

    @Override
    protected boolean isShownTabs() {
        return false;
    }

    @Override
    protected boolean isShownTopBar() {
        return true;
    }


    @Override
    public void onSwiperPlugOff() {
        HPLog.i("VPOSActivity", "----onSwiperPlugOff--mAction:" + mAction);
        ClientEngine.getInstance().saveGlobal(IBusinessSwiper.BANK_TransactionType_KEY, null);
        clearFactor();
        stopAdpu();
        // 如果是超级转账或者查询余额，直接返回到功能主界面
        if (ZZTongActivity.Action_SuperTransfer == mAction || ZZTongActivity.Action_BalanceEnquiry == mAction || ZZTongActivity.Action_CreditCardRepay == mAction || mAction == ZZTongActivity.Action_SuperUniTrans) {
            onFunctionTab(null);
        } else {
            // 如果是刷卡转账，直接返回到输入金额界面
            onTransferTab(null);
        }
        goBack();
    }


    /**
     * 刷新状态
     */
    private Handler hRefreshStatus = new VPOSHandler(this);

    /**
     * 只负责显示界面。不做刷卡器操作
     */
    static class VPOSHandler extends Handler {
        private final WeakReference<VPOSActivity> mBaseActivity;

        public VPOSHandler(VPOSActivity activity) {
            mBaseActivity = new WeakReference<VPOSActivity>(activity);
        }

        public BaseActivity getActivity() {
            return mBaseActivity.get();
        }

        @Override
        public void handleMessage(Message msg) {
            final VPOSActivity activity = (VPOSActivity) getActivity();
            if (null == activity) {
                return;
            }
            int status = msg.getData().getInt("status");
            switch (status) {
                case ISwiperListener.Status_Swipe:// 等待刷卡
                    HPLog.i("VPOSActivity", "等待刷卡-------------");
                    long startTime = SystemClock.elapsedRealtime();
                    //暂时这么判断，以后需要根据刷卡器类型，来显示刷卡界面
                    View cardView;
                    if (null != ApiSwiperFactory.getInstance().getSwiperModel() && !ApiSwiperFactory.getInstance().getSwiperModel().mSupportSwiper) {
                        // 音频
                        SwiperCardVoiceView swiperCardView2 = new SwiperCardVoiceView(activity, null);
                        HPLog.i("VPOSActivity", "new SwiperCardView: not mSupportPwd");
//                        swiperCardView2.setVisibility(1);
                        swiperCardView2.setIsSwiperOn(true);
                        swiperCardView2.setBackListener(new BackListener() {

                            @Override
                            public void back() {
                                ((VPOSActivity) getActivity()).onClick(null);
                            }
                        });
                        cardView = swiperCardView2;
                    } else {
                        // 蓝牙
                        activity.swiperCardView = new SwiperCardBluetoothView(activity, null);
                        HPLog.i("VPOSActivity", "new SwiperCardView: mSupportPwd");
                        cardView = activity.swiperCardView;
                    }

                    // sw.setVisibility(0);
                    if (0 != activity.llContent.getChildCount()) {
                        activity.llContent.removeAllViews();
                    }
                    HPLog.i("VPOSActivity", "remove : " + (SystemClock.elapsedRealtime() - startTime));
                    activity.llContent.addView(cardView);
                    HPLog.i("VPOSActivity", "addView : " + (SystemClock.elapsedRealtime() - startTime));
                    break;
                case ISwiperListener.Status_InputPwdRegister:// 等待输入密码
                case ISwiperListener.Status_InputPwdTrade: { // 等待输入密码
                    HPLog.i("VPOSActivity", "等待输入密码-------------");
                    boolean hasKeyBoard = msg.getData().getBoolean("hasKeyBoard", false);
                    if (hasKeyBoard) {
                        HPLog.i("VPOSActivity", "等待输入密码-------------键盘");
                        showPwdKeyBoardView(activity);
                    } else {
                        HPLog.i("VPOSActivity", "等待输入密码-------------没有键盘");
                        showPwdViewNoKeyBoard(activity);
                    }
                    break;
                }
                case ISwiperListener.Status_AffirmAmount:// 等待确认金额
                {
                    HPLog.i("VPOSActivity", "等待确认金额-------------");
                    ViewGroup view = (ViewGroup) LayoutInflater.from(activity).inflate(R.layout.layout_security_key_board, null);
                    TextView tvWarning = (TextView) view.findViewById(R.id.text_warning);
                    tvWarning.setText(R.string.please_confirm_money);
                    activity.llContent.removeAllViews();
                    activity.llContent.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                }
                break;
                case ISwiperListener.Status_Four_Elements: {
                    activity.myActionBar.setVisibility(View.VISIBLE);
                    // activity.myActionBar.setTitleText(R.string.four_element_title);
                    ViewGroup view = (ViewGroup) LayoutInflater.from(activity).inflate(R.layout.layout_four_element, null);
                    activity.llContent.removeAllViews();
                    activity.llContent.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                    final FourElementsScreen four_element_screen = (FourElementsScreen) view.findViewById(R.id.four_element_screen);
                    amV = total / 100.00;
                    DecimalFormat decimalFormat = new DecimalFormat(".00");// 构造方法的字符格式这里如果小数不足2位,会以0补足.
                    String p = decimalFormat.format(amV);
                    four_element_screen.four_element_amount_tv.setText(p);
                    String plainAccount = activity.mBankInfoHashMap.get(IBusinessSwiper.BANK_PLAIN_ACCOUNT_KEY);

                    four_element_screen.four_element_bank_no_tv.setText(CommonUtils.formattingCard_4(plainAccount));
                    four_element_screen.four_element_bank_no = plainAccount;
                    four_element_screen.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            activity.doCheckSwipeCardFourElements(four_element_screen.four_element_bank_no, four_element_screen.four_element_name, four_element_screen.four_element_id_no, four_element_screen.four_element_mobile_no);
                        }
                    });
                }
                break;
            }
        }

        static void showPwdViewNoKeyBoard(final VPOSActivity activity) {
            ViewGroup view = (ViewGroup) LayoutInflater.from(activity).inflate(R.layout.nokeyboard, null);
            activity.llContent.removeAllViews();
            activity.llContent.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        }

        /**
         * 显示带键盘的输入密码界面
         *
         * @param activity
         */
        static void showPwdKeyBoardView(final VPOSActivity activity) {
            ViewGroup view = (ViewGroup) LayoutInflater.from(activity).inflate(R.layout.pwdscreen, null);
            PWDScreen2 pwdScreen = (PWDScreen2) view.findViewById(R.id.pwdView);
            amV = total / 100.00;
            HPLog.i("result", "转账金额:" + amount);
            DecimalFormat decimalFormat = new DecimalFormat(".00");// 构造方法的字符格式这里如果小数不足2位,会以0补足.
            String p = decimalFormat.format(amV);
            pwdScreen.amountValueVisibily(isShowAmount ? View.VISIBLE : View.GONE, p);
            pwdScreen.setPwdClickListener(new ClickListener() {
                @Override
                public void onClick(int type, String pwd) {
                    if (type == 0) {
                        ApiSwiperFactory.getInstance().doSetPwd(null, activity.getId());
                        activity.onClick(null);
                    } else {
                        // 避免短时间内多次调用
                        if (SystemClock.elapsedRealtime() - mLastClickTime < 4000) {
                            HPLog.e("Test", "不能连续操作-------------");
                            return;
                        }
                        mLastClickTime = SystemClock.elapsedRealtime();
                        if (SwiperUtils.isSwiperConnected()) {
                            activity.showProgressDialog(activity, activity.getString(R.string.pleasewait));
                            ApiSwiperFactory.getInstance().doSetPwd(pwd, activity.getId());
                        } else {
                            Toast.makeText(activity, activity.getString(R.string.device_failed), Toast.LENGTH_LONG).show();
                            activity.onClick(null);
                        }
                    }
                }
            });
            pwdScreen.setCloseListener(new CloseListener() {
                @Override
                public void onClick() {
                    ApiSwiperFactory.getInstance().doSetPwd(null, activity.getId());
                    activity.onClick(null);
                }
            });
            HPLog.i("VPOSActivity", "add keyboard");
            activity.llContent.removeAllViews();
            activity.llContent.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        }
    }

    protected boolean isVisiableTopBar() {
        return false;
    }

    protected void refreshStatus(int status) {
        HPLog.e("refreshStatus", "" + status);
        Bundle data = new Bundle();
        data.putInt("status", status);
        Message msg = new Message();
        msg.setData(data);
        hRefreshStatus.sendMessage(msg);
    }

    /**
     * 显示一个是否带键盘的刷卡器。
     *
     * @param hasKeyBoard true表示，显示带键盘的界面，否则显示一个不带键盘的界面
     */
    protected void refreshPwdScreen(boolean hasKeyBoard) {
        HPLog.e("refreshPwdScreen", "" + hasKeyBoard);
        Bundle data = new Bundle();
        data.putInt("status", ISwiperListener.Status_InputPwdTrade);
        data.putBoolean("hasKeyBoard", hasKeyBoard);
        Message msg = new Message();
        msg.setData(data);
        hRefreshStatus.sendMessage(msg);
    }

    private void doNext(String account, String plainAcount, String pin, String track2, String track3, String encAmount, String random, String dcdata, String icnumber, String mac, String expireDate) {
        HPLog.e("doNext", "action:" + mAction);
        if (mAction == ZZTongActivity.Action_BalanceEnquiry) {
            //  客户端直接测试银联. 必须是新刷卡器才可以做银联余额查询
            if (ZZTConfig.ENV.BALANCE_ENQUIRE_UP) {
                String data = getFactorTime() + " " + account + " " + track2 + " " + getCSN();
                mAccount = account;
                mPin = pin;
                this.mDyKey = random;
                this.mTrack2 = track2;
                doMac(data);
            } else {
                // ---------------------------------------------
                Hashtable<String, String> params = new Hashtable<String, String>();
                if (checkStrIsNull(account, pin)) {
                    HPLog.e("checkStrIsNull", "Vpos:doNext account:" + account + ":pin" + pin);
                    return;
                }

                params.put(AQProtocolConstant.OUT_CARD_KEY, account);
                params.put(AQProtocolConstant.PWD_KEY, pin);
                // IC卡，没有磁道二。格尔的磁道加密，可能没有dynamicKeyData
                if (!TextUtils.isEmpty(track2)) {
                    params.put(AQProtocolConstant.TRACK2_KEY, track2);
                }
                if (!TextUtils.isEmpty(random)) {
                    params.put("dynamicKeyData", random);
                }
                toNull();
                String csn = SwiperUtils.getCsn();
                params.put(AQProtocolConstant.CSN_KEY, SecureManager.getInstance().des(csn, 1, null));
                params.put(AQProtocolConstant.FACTOR_KEY, getFactor());
                params.put(AQProtocolConstant.CHANNEL, ClientEngine.CHANNEL);
                params.put(AQProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
                appendAddresses(params, true);
                if (!ApiSwiperFactory.getInstance().isSingleKey()) {
                    doJsonPost(this, Do_BalanceEnquiry, MicroBalanceQueryBean.class, params);
                } else {
                    if (!TextUtils.isEmpty(dcdata)) {
                        params.put(ICCardConstant.DC_DATA_KEY, dcdata);
                        if (!TextUtils.isEmpty(icnumber)) {
                            params.put(ICCardConstant.IC_NUM_KEY, icnumber);
                        }
                        HPLog.i(HPLog.FDL_TAG, "expireDate后台Action_BalanceEnquiry交互" + expireDate);
                        params.put("mac", mac);
                    }
                    HPLog.i("Bbpos_ME368", "Action_BalanceEnquiry后台交互");
                    doJsonPost(this, Do_BalanceEnquiry20, MicroBalanceQueryBean.class, params);
                }
            }

        } else if (mAction == ZZTongActivity.Action_Transfer1 || mAction == ZZTongActivity.Action_SameTransfer1 || mAction == ZZTongActivity.Action_MARKET) {
            String address = (String) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_ADDRESS);
            if (!TextUtils.isEmpty(address)) {
                zztTransfer(account, plainAcount, pin, track2, track3, encAmount, random, dcdata, icnumber, mac, expireDate);
            } else {
                getCurrentLocation();
            }
        } else if (mAction == ZZTongActivity.Action_SuperTransfer || mAction == ZZTongActivity.Action_CreditCardRepay || mAction == ZZTongActivity.Action_SuperUniTrans) {
            // 记录一些必要数据
            // this.doUPcardMac();
            mAccount = account;
            this.mPlainAccount = plainAcount;
            mPin = pin;
            this.mTrack2 = track2;
            this.mEncAmount = encAmount;
            this.mDyKey = random;
            this.mICNum = icnumber;
            this.mDCData = dcdata;
            this.mexpireDate = expireDate;
            HPLog.i("result", "mAccount:" + mAccount);
            HPLog.i("result", "mPlainAccount:" + mPlainAccount);
            HPLog.i("result", "mTrack2:" + mTrack2);
            HPLog.i("result", "mEncAmount:" + mEncAmount);
            HPLog.i("result", "mDyKey:" + mDyKey);
            HPLog.i("result", "mICNum:" + mICNum);
            HPLog.i("result", "mDCData:" + mDCData);
            HPLog.i("result", "mexpireDate:" + mexpireDate);
            HPLog.i("result", "mTerminalId:" + mTerminalId);
            // 开始数据的加密流程
            this.showProgressDialog(this, getString(R.string.pleasewait));
            //银联转账没有mTerminalId 不需要去加密
            if (!TextUtils.isEmpty(mTerminalId)) {
                doEncryData(mTerminalId);
            } else {
                doEncryData(mChannelOrderCurrency);
            }

        } else if (mAction == ZZTongActivity.Action_Phone || mAction == ZZTongActivity.Action_Qb || mAction == ZZTongActivity.Action_Game) {
            String time = getFactor().substring(0, 14);
            this.merchantId = (String) ClientEngine.getInstance().getGlobal(IBusinessSwiper.BANK_MerchantID_KEY);
            String merchantName = ShowHtmlActivity.map.get("merchantName");
            String merchantCountry = ShowHtmlActivity.map.get("merchantCountry");
            this.mTerminalId = (String) ClientEngine.getInstance().getGlobal(IBusinessSwiper.BANK_TerminalID_KEY);
            this.orderId = (String) ClientEngine.getInstance().getGlobal(IBusinessSwiper.BANK_OrderID_KEY);
            this.mEncAmount = (String) ClientEngine.getInstance().getGlobal(IBusinessSwiper.BANK_TransAmount_KEY);
            mPin = pin;
            mAccount = account;
            this.mTrack2 = track2;
            String csn = (String) ClientEngine.getInstance().getGlobal("CSN");
            this.mDyKey = random;
            this.mICNum = icnumber;
            this.mDCData = dcdata;
            String xml = UPXMLReqComposer.xmlPurchaseAdvice(time, merchantId, merchantName, merchantCountry, mTerminalId, orderId, mEncAmount, account, pin, track2, csn, random, icnumber, dcdata, mac, expireDate);
            HPLog.e("xml", xml);
            new Thread(new WebService(xml)).start();
        }
    }

    private AlertDialog mSelectICApp;

    @Override
    public void showSelectICApp(final ArrayList<String> cardTypes, final IICSelectApplicationCallback selectApplicationCallback) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                final ArrayList<String> availableName = new ArrayList<String>();
                for (String name : cardTypes) {
                    // 超级转账的时候，不允许信用卡
                    if (getString(R.string.card_credit).equals(name) && (mAction == Action_SuperTransfer || mAction == Action_SuperUniTrans)) {
                        HPLog.i("showSelectICApp", "ignore " + name + " mAction:" + mAction);
                    } else {
                        HPLog.i("showSelectICApp", "Add " + name + " mAction:" + mAction);
                        if (name.contains("CREDIT")) {
                            availableName.add(VPOSActivity.this.getString(R.string.card_credit));
                        } else if (name.contains("DEBIT")) {
                            availableName.add(VPOSActivity.this.getString(R.string.card_debit));
                        } else {
                            availableName.add(name);
                        }

                    }
                }
                if (0 == availableName.size()) {
                    // 提醒没得选择
                    showNoAvailableApp(new Runnable() {
                        @Override
                        public void run() {
                            selectApplicationCallback.onCardTypeSelect(-1);
                        }
                    });
                } else if (1 == availableName.size()) {
                    // 只有一个可以选择，帮助用户选择
                    int index = cardTypes.indexOf(availableName.get(0));
                    selectApplicationCallback.onCardTypeSelect(index);
                } else {
                    AlertDialog.Builder ab = new AlertDialog.Builder(VPOSActivity.this);
                    ab.setCancelable(false);
                    ab.setAdapter(new ArrayAdapter<String>(VPOSActivity.this, R.layout.simple_list_item, availableName), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            int index = cardTypes.indexOf(availableName.get(i));
                            selectApplicationCallback.onCardTypeSelect(index);
                        }
                    });
                    ab.setTitle(R.string.please_select_card_type);
                    mSelectICApp = ab.create();
                    mSelectICApp.show();
                }
            }
        });
    }

    @Override
    public void showNoAvailableApp(final Runnable r) {
        this.showAlertDialog(this, getString(R.string.tip_title), getString(R.string.no_available_card), false, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                r.run();
            }
        });
    }

    @Override
    public void closeSelectICApp() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (mSelectICApp != null) {
                        HPLog.i("", "actually dismiss mSelectICApp dialog");
                        mSelectICApp.dismiss();
                        mSelectICApp = null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mSelectICApp = null;
                }
            }
        });
    }

    /**
     * 超级转账交易转出卡实名认证
     */
    private void TransferCardAuthentication() {
        //  向后台做一次查询，如果存在，直接消费成功，如果不存在，做实民认证；
        Hashtable<String, String> param = new Hashtable<String, String>();
        param.put("channel", ClientEngine.CHANNEL);
        String csn = SwiperUtils.getCsn();
        param.put("csn", csn);
        // 转出卡明文Des加密
        param.put("cardNum", SecureManager.getInstance().des(mPlainAccount, 1, null));
        doPost(this, Do_QueryHXFourElements, param);
    }

    /**
     * 超级转账
     */
    private void superTransfer(String encMac) {
        HPLog.i("result", "encMac:" + encMac);
        HPLog.e("zztTransfer", "superTransfer");
        Hashtable<String, String> params = new Hashtable<String, String>();
        /***
         *  不传默认为快速转账；
         *   类型为枚举:
         *   1:快速转账；
         *   2:银联转账；
         */
        if (ZZTongActivity.Action_SuperUniTrans == mAction) {
            params.put("transChannel", "2");
        }
        // 刷卡器加密:
        // params.put("terminalId", this.mDesTerminalId);
        params.put("terminalId", mTerminalId);
        HPLog.i("result", "terminalId:" + mTerminalId);
        // 交易时间
        String time = getFactorTime();
        params.put("transTime", time);
        HPLog.i("result", "transTime:" + time);
        // 订单总额，des加密
        BigDecimal bd = new BigDecimal(total);
        String strTotal = bd.toString();
        HPLog.i("result", "channelOrderAmt:" + strTotal);
        params.put("channelOrderAmt", SecureManager.getInstance().des(strTotal, 1, null));
        // 订单总额，刷卡器加密
        params.put("encryAmt", mEncAmount);
        HPLog.i("result", "encryAmt:" + mEncAmount);
        // 交易币种
        params.put("channelOrderCurrency", mChannelOrderCurrency);
        // 交易币种，刷卡器加密
        HPLog.i("result", "mEncryCurrency:" + mEncryCurrency);
        params.put("encryCurrency", mEncryCurrency);
        // 转出卡明文Des加密
        params.put("cardNum", SecureManager.getInstance().des(mPlainAccount, 1, null));
        // 转出卡明文刷卡器加密
        params.put("accountNumber1", mAccount);
        HPLog.i("result", "accountNumber1:" + mAccount);

        // 转出卡密码刷卡器加密
        params.put("pan", mPin);
        // 刷卡器获取
        if (!TextUtils.isEmpty(mTrack2)) {
            params.put("track2Data", mTrack2);
            HPLog.i("result", "track2Data:" + mTrack2);
        }
        if (!TextUtils.isEmpty(mDCData)) {
            params.put(ICCardConstant.DC_DATA_KEY, mDCData);
            HPLog.i("result", "mDCData:" + mDCData);
            if (!TextUtils.isEmpty(mICNum)) {
                HPLog.i("result", "mICNum:" + mICNum);
                params.put(ICCardConstant.IC_NUM_KEY, mICNum);
            }
        }
        // 转入账号明文DES加密
        params.put("acccountNum", SecureManager.getInstance().des(mTransferInAccount.getCardPlainNo(), 1, null));
        // 转入账号，刷卡器加密
        params.put("accountNumber2", mEncEncryAccountNum2);
        HPLog.i("result", "accountNumber2:" + mEncEncryAccountNum2);
        // 转账费率fee，des 加密
        Double fee = total - amount;
        HPLog.i(HPLog.SSX_TAG, "手续费:" + fee);
        params.put("fee", SecureManager.getInstance().des(String.valueOf(fee.intValue()), 1, null));
        // BUG: 由于找不到服务器端长时间没响应返回，用户再次发起发送请求的路径。暂时把csn的des加密放到一起，减少des变化造成的原因。
        // 但是，这里还是有可能出现bug的。
        // 如何确保这些数据des加密密钥都一样，并且在密钥交换的时候，发送给服务器进行交换的也是这个密钥？
        // csn des加密
        String csn = SwiperUtils.getCsn();
        String cardSerialNumber = SecureManager.getInstance().des(csn, 1, null);
        // csn des加密
        params.put("cardSerialNumber", cardSerialNumber);
        // 刷卡器获取
        params.put("dynamicKeyData", mDyKey);
        HPLog.i("result", "dynamicKeyData:" + mDyKey);
        // 收款人姓名
        params.put("accountName", SecureManager.getInstance().des(mTransferInAccount.getCardName(), 1, null));
        // channel
        params.put("channel", ClientEngine.CHANNEL);
        // 位置信息
        appendAddresses(params, true);
        // 账户名
        String desAcc = SecureManager.getInstance().des(AccountUtils.getAccountName(this), 1, null);
        params.put(ATProtocolConstant.ACCOUNT, desAcc);
        // Mac加密
        params.put("mac", encMac);
        params.put(BaseProtocolKey.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);

        HPLog.e(HPLog.FDL_TAG, "VPOSActivity---------superTransfer--------");
        // 新版2.0.0 添加IC卡有效期

        if (!TextUtils.isEmpty(mexpireDate) && CommonUtils.isLegalExpireDate(mexpireDate)) {
            HPLog.e(HPLog.FDL_TAG, "VPOSActivity---------superTransfer--------mexpireDate" + mexpireDate);
            // if (!checkExpireDate(mexpireDate)) {
            // finishDialog(getString(R.string.ic_expire_date_error));
            // return;
            // }
            HPLog.i("result", "mexpireDate:" + mexpireDate);
            params.put("expireDate", SecureManager.getInstance().des(mexpireDate, 1, null));
        }

        doJsonPost(this, Do_SubatmTransfer, AccountTransfer.class, params);
    }

    private boolean checkStrIsNull(String... obj) {
        for (String str : obj) {
            if (TextUtils.isEmpty(str)) {
                dealError();
                return true;
            }
        }
        return false;
    }

    private void zztTransfer(String account, String plainAccount, String pin, String track2, String track3, String encAmount, String dynamicKeyData, String dcdata, String icnumber, String mac, String expireDate) {
        HPLog.e("zztTransfer", "zztTransfer");
        if (checkStrIsNull(account, plainAccount, pin, encAmount)) {
            HPLog.e("checkStrIsNull", account + ":" + plainAccount + ":" + pin + ":" + track2 + ":" + track3 + ":" + encAmount + ":" + dynamicKeyData + ":" + dcdata + ":" + icnumber + ":" + mac);
            return;
        }
        Hashtable<String, String> params = new Hashtable<String, String>();

        // 转出卡号；刷卡器加密
        params.put(ATProtocolConstant.OUT_CARD_KEY, account);

        // 银行卡密码；刷卡器加密
        params.put(ATProtocolConstant.PWD_KEY, pin);

        // 2磁道
        // IC卡，没有磁道二
        if (!TextUtils.isEmpty(track2)) {
            params.put(AQProtocolConstant.TRACK2_KEY, track2);
        }
        if (!TextUtils.isEmpty(dynamicKeyData)) {
            params.put("dynamicKeyData", dynamicKeyData);
        }
        params.put(ATProtocolConstant.AMOUNT_KEY, encAmount);
        toNull();
        String csn = SwiperUtils.getCsn();
        String factor = getFactor();
        // 账户名
        String desAcc = SecureManager.getInstance().des(AccountUtils.getAccountName(this), 1, null);
        if (checkStrIsNull(csn, factor, desAcc)) {
            HPLog.e("checkStrIsNull", "csn=" + csn + ",factor =" + factor + ",desAcc=" + desAcc);
            return;
        }
        // csn
        params.put(ATProtocolConstant.CSN_KEY, SecureManager.getInstance().des(csn, 1, null));
        // factor
        params.put(ATProtocolConstant.FACTOR_KEY, factor);
        // 渠道
        params.put(ATProtocolConstant.CHANNEL, ClientEngine.CHANNEL);
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
        params.put(ATProtocolConstant.CLIENTVERSION, "v" + ClientEngine.VERSION);
        if (!isRateNull) {
            HPLog.i(HPLog.FDL_TAG, "zztTransfer后台交互--selectedRate=" + selectedRate + "----isPublicCharge=" + isPublicCharge);
            params.put(ATProtocolConstant.RATECODE, SecureManager.getInstance().des(selectedRate + "", 1, null));
            params.put(ATProtocolConstant.ISPUBILCCHARGE, isPublicCharge + "");
        }
        // 位置信息
        appendAddresses(params, true);
        params.put(ATProtocolConstant.ACCOUNT, desAcc);
        if (!TextUtils.isEmpty(expireDate) && CommonUtils.isLegalExpireDate(expireDate)) {
            params.put("expireDate", SecureManager.getInstance().des(expireDate, 1, null));
        }
        params.put("isOpen", iOriginIsOpenNeedCamera + "");
        params.put("isOCardAuth", iOriginIsOpenFourElements + "");
        if (!ApiSwiperFactory.getInstance().isSingleKey()) {
            doJsonPost(this, DO_AccountTransfer, AccountTransfer.class, params);
        } else {
            if (!TextUtils.isEmpty(dcdata)) {
                // IC
                params.put(ICCardConstant.DC_DATA_KEY, dcdata);
                if (TextUtils.isEmpty(icnumber)) {
                    icnumber = "000";
                }
                params.put(ICCardConstant.IC_NUM_KEY, icnumber);
                params.put("mac", mac);
            }

            if (mAction == Action_MARKET) {
                params.put("orderNo", SecureManager.getInstance().des(orderNo, 1, null));
                params.put("transSeq", SecureManager.getInstance().des(transSeq, 1, null));
                HPLog.i(HPLog.YL_TAG, "分销系统" + params.toString());
                doJsonPost(this, DO_MarketAccountTransfer, AccountTransfer.class, params);
            } else {
                HPLog.i(HPLog.YL_TAG, "zztTransfer后台交互" + params.toString());
                doJsonPost(true, this, DO_AccountTransfer20, AccountTransfer.class, params, true);
            }
        }
    }

    @Override
    public boolean netJsonResponse(String action, ResponseBean resp, boolean showAlert) {
        boolean result = super.netJsonResponse(action, resp, showAlert);
        if (result) {
            return true;
        }
        if (Do_GetBusinessControlSwitch.equals(action)) {
            this.closeProgressDialog();
            BusinessControlSwitch businessControlSwitch = (BusinessControlSwitch) resp;
            if (businessControlSwitch != null) {
                // switchType 开关类型 0:刷卡收款四要素,1：转出卡拍照
                // isOpen 开关是否打开状态 1:表示打开,0:表示关闭
                Map<Integer, Integer> maps = new HashMap<Integer, Integer>();
                if (businessControlSwitch.getList() != null) {
                    for (BusinessControlSwitch.ListBean item : businessControlSwitch.getList()) {
                        int switchType = item.getSwitchType();
                        int isOpen = item.getIsOpen();
                        maps.put(switchType, isOpen);
                    }
                    iIsOpenFourElements = getMapKeyToValue(maps, 0);
                    iOriginIsOpenFourElements = getMapKeyToValue(maps, 0);
                    iIsOpenNeedCamera = getMapKeyToValue(maps, 1);
                    iOriginIsOpenNeedCamera = getMapKeyToValue(maps, 1);
                    isUinPayOpenFourElements = getMapKeyToValue(maps, 5);
                    iIsOpenCardScanCamera = getMapKeyToValue(maps, 4);
                    iOriginIsOpenCardScanCamera = getMapKeyToValue(maps, 4);

                }
            }
            HPLog.i(HPLog.YL_TAG, "Do_GetBusinessControlSwitch IsOpenFourElements：" + iIsOpenFourElements + "IsOpenNeedCamera：" + iIsOpenNeedCamera + "isUinPayOpenFourElements:" + isUinPayOpenFourElements);
            doCheckBusinessControlSwitch();

        } else if (DO_AccountTransfer.equals(action) || action.equals(DO_AccountTransfer20) || Do_SubatmTransfer.equals(action) || action.equals(DO_MarketAccountTransfer)) {
            AccountTransfer bean = (AccountTransfer) resp;
            boolean isError = false;
            Bill.APPCODE appCode;
            if (DO_AccountTransfer.equals(action) || action.equals(DO_AccountTransfer20)) {
                appCode = Bill.APPCODE.TRANS;
            } else if (action.equals(DO_MarketAccountTransfer)) {
                appCode = Bill.APPCODE.MARKET_TRANS;
            } else {
                appCode = Bill.APPCODE.SUPER_TRANS;
            }
            Bill bill = CommonUtils.generateBill(bean, appCode);
            HPLog.i(HPLog.SSX_TAG, bill.toString());
            bill.setTradeType(Bill.TRAD_TYPE_POSPAY);
            Intent intent = new Intent();
            intent.putExtra(ACTION, this.mAction);
            if (Bill.APPCODE.TRANS == appCode || Bill.APPCODE.MARKET_TRANS == appCode) {
                //收款交易消费卡信息采集 成功之后才操作
                if (!TextUtils.isEmpty(bill.getCardNoOutFull()) && !TextUtils.isEmpty(bill.getTransSN()) && !TextUtils.isEmpty(bill.getMerchantCode())) {
                    upLoadBankCardPic(fileUrl, bill.getCardNoOutFull(), bill.getTransTime(), bill.getTransSN(), bill.getMerchantCode(), cardImageNumber, false, false);
                }
                if (Bill.STATUS_SUCCESS == bill.getStatus()) {
                    intent.setClass(this, TransResultSuccessActivity.class);
                    if (TextUtils.isEmpty(bill.getTerminalNo())) {
                        bill.setTerminalNo(getCSN());
                    }
                } else {
                    HPLog.i(HPLog.YL_TAG, "收款交易失败");
                    intent.setClass(this, TransResultFailureActivity.class);
                }
            } else {
                if (bill.getStatus() == Bill.STATUS_FAILED) {
                    byte action_from = this.getIntent().getByteExtra(ZZTongActivity.ACTION_FROM, (byte) 0);
                    if (action_from == ZZTongActivity.Action_FROM_CREDIT) {
                        intent.putExtra(ZZTongActivity.ACTION_FROM, ZZTongActivity.Action_FROM_CREDIT);
                    }
                    intent.setClass(this, TradingResultsFailed.class);
                } else {
                    if (this.mAction == ZZTongActivity.Action_SuperUniTrans) {
                        byte action_from = this.getIntent().getByteExtra(ZZTongActivity.ACTION_FROM, (byte) 0);
                        if (action_from == ZZTongActivity.Action_FROM_CREDIT) {
                            intent.putExtra(ZZTongActivity.ACTION_FROM, ZZTongActivity.Action_FROM_CREDIT);
                        }
                    }
                    intent.setClass(this, TradingResults.class);
                }
                if (mTransferInAccount != null) {
                    intent.putExtra(TradingResults.KEY_NAME, mTransferInAccount.getCardName());
                } else {
                    isError = true;
                }
            }
            if (isError) {
                dealError();
            } else {
                intent.putExtra(ACTION, this.mAction);
                intent.putExtra(QueryBillsActivity.billvalue, bill);
                if (action.equals(ZZTongActivity.DO_MarketAccountTransfer)) {
                    String pageUrl = bean.getPageUrl();
//                    HPLog.i(HPLog.YL_TAG, "pageUrl:" + pageUrl);
                    intent.putExtra("pageUrl", SecureManager.getInstance().des(pageUrl, 0, null));
                }
                startActivity(intent);
                onClick(null);
            }
        } else if (Do_CheckSwipeCardFourElements.equals(action)) {

            CheckSwipeCardFourElements bean = (CheckSwipeCardFourElements) resp;

            Log.i(HPLog.YL_TAG, "------------Do_CheckSwipeCardFourElements---------------");
//            int responseCode = CommonUtils.objectToInt(luaTable.rawget("responseCode"));

            String status = (String) bean.getStatus();
            if (status.equals("1")) {
                // doPreNext();
                iIsOpenFourElements = 0;
                isUinPayOpenFourElements = 0;
                doCheckBusinessControlSwitch();
            } else if (status.equals("0")) {
                Intent intent = new Intent();
                if (this.mAction == ZZTongActivity.Action_SuperUniTrans) {
                    Bill bill = new Bill();
                    String transSN = bean.getTransSN();
                    String cardNoOut = bean.getCardNo();
                    String transTime = bean.getTransTime();
                    String transStatus = bean.getMessage();
                    bill.setTradeType(Bill.TRAD_SUPER_UNIPAY);
                    bill.setCardNoOut(CommonUtils.formattingCard_4(cardNoOut));
                    bill.setCardNoIn(CommonUtils.formattingCard_4(mTransferInAccount.getCardPlainNo()));
                    bill.setTransTime(transTime);
                    bill.setTransSN(transSN);
                    bill.setTransChannel("2");
                    bill.setTransStatus(transStatus);
                    intent.putExtra(TradingResultsFailed.KEY_NAME, mTransferInAccount.getCardPlainNo());
                    intent.putExtra(ACTION, this.mAction);
                    HPLog.i(HPLog.SSX_TAG, bill.toString());
                    byte action_from = this.getIntent().getByteExtra(ZZTongActivity.ACTION_FROM, (byte) 0);
                    if (action_from == ZZTongActivity.Action_FROM_CREDIT) {
                        intent.putExtra(ACTION_FROM, action_from);
                    }
                    intent.setClass(this, TradingResultsFailed.class);
                    intent.putExtra(QueryBillsActivity.billvalue, bill);
                } else {
                    intent.setClass(this, TransResultFourElementsFailureActivity.class);
                    Bill bill = new Bill();
                    bill.setAppcode(Bill.APPCODE.TRANS);
                    bill.setStatus(Integer.valueOf(status).intValue());
                    bill.setCardNoOut(CommonUtils.formattingCard_4(bean.getCardNo()));
                    bill.setTransTime(bean.getTransTime());
                    bill.setTransSN(bean.getTransSN());
                    bill.setTransStatus(bean.getMessage());
                    bill.setAmount(total);
                    intent.putExtra(QueryBillsActivity.billvalue, bill);
                }
                startActivity(intent);
                goBack();

            }
        } else if (action.equals(Do_BalanceEnquiry) || action.equals(Do_BalanceEnquiry20)) {
            MicroBalanceQueryBean microBalanceQueryBean = (MicroBalanceQueryBean) resp;
            Intent intent = new Intent(VPOSActivity.this, BalanceEnquiry.class);
            Double balance = CommonUtils.objectToDouble(microBalanceQueryBean.getBalance());
            String cardNo = microBalanceQueryBean.getCardNo();
            String bankName = microBalanceQueryBean.getBankName();
            String bankType = microBalanceQueryBean.getBankType();
            intent.putExtra(AQProtocolConstant.OUT_BALANCE, balance);
            intent.putExtra(AQProtocolConstant.OUT_CARD_NO, cardNo);
            intent.putExtra(AQProtocolConstant.OUT_BANKNAME, bankName);
            intent.putExtra(AQProtocolConstant.OUT_BANKTYPE, bankType);
            startActivity(intent);
            onClick(null);
        } else if (action.equals(Do_SubatmQueryFee)) {
            MicroSuperFeeBean microSuperFeeBean = (MicroSuperFeeBean) resp;
            // 显示订单界面
            BigDecimal fee = microSuperFeeBean.getFee();
            total = amount + fee.doubleValue();
            mTerminalId = microSuperFeeBean.getTerminalId();
            if (!TextUtils.isEmpty(mTerminalId)) {
                this.mTerminalId = SecureManager.getInstance().des(mTerminalId, 0, null);
            } else {
                HPLog.e("VPOSActivity", "terminalId null");
            }
            showTransConfirmDialog();
        }
        return true;
    }

    @Override
    public boolean netResponse(String action, Hashtable<String, Object> resp, boolean showAlert) {
        HPLog.i(HPLog.YL_TAG, "response action:" + action);
        closeProgressDialog();
        //业务开关不走基类的判断。如果网络请求有问题有默认参数。
        if (!action.equals(Do_GetBusinessControlSwitch) && super.netResponse(action, resp, showAlert, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                VPOSActivity.this.goBack();
            }
        })) {
            return true;
        }
        byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);

        LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
        if (action.equals(Do_BalanceEnquiry) || action.equals(Do_BalanceEnquiry20) || action.equals(UPConfig.UPHost)) {
            // 余额查询
            Intent intent = new Intent(VPOSActivity.this, BalanceEnquiry.class);
            Double balance = 0d;
            String cardNo = "";
            String bankName = "";
            String bankType = "";
            if (action.equals(UPConfig.UPHost)) {
                Hashtable<String, String> responseData = UPXMLRespParser.getInstance().parseResp((byte[]) resp.get(HttpEngine.Key_RespData));
                if (null != responseData && UPXMLRespParser.RESPOK.equals(responseData.get(UPXMLRespParser.XPRESPCODE.toLowerCase(Locale.US)))) {
                    String accountBalance = responseData.get(UPXMLRespParser.XPACCOUNTBALANCE.toLowerCase(Locale.US));
                    balance = Double.parseDouble(accountBalance);
                    cardNo = mPlainAccount;
                    bankName = "";
                    bankType = "";
                } else {
                    ClientEngine.showToast(this, "查询手续费失败! reponseCode: " + responseData.get(UPXMLRespParser.XPRESPCODE.toLowerCase(Locale.US)));
                }
            } else {
                balance = Double.parseDouble((String) luaTable.rawget(AQProtocolConstant.OUT_BALANCE));
                cardNo = (String) luaTable.rawget(AQProtocolConstant.OUT_CARD_NO);
                bankName = (String) luaTable.rawget(AQProtocolConstant.OUT_BANKNAME);
                bankType = (String) luaTable.rawget(AQProtocolConstant.OUT_BANKTYPE);
            }
            intent.putExtra(AQProtocolConstant.OUT_BALANCE, balance);
            intent.putExtra(AQProtocolConstant.OUT_CARD_NO, cardNo);
            intent.putExtra(AQProtocolConstant.OUT_BANKNAME, bankName);
            intent.putExtra(AQProtocolConstant.OUT_BANKTYPE, bankType);
            startActivity(intent);
            onClick(null);
        } else if (action.equals(Do_SubatmQueryFee)) {
            // 显示订单界面
            double fee = Double.parseDouble(String.valueOf(luaTable.rawget("fee")));
            total = amount + fee;
            mTerminalId = (String) luaTable.rawget("terminalId");
            if (!TextUtils.isEmpty(mTerminalId)) {
                this.mTerminalId = SecureManager.getInstance().des(mTerminalId, 0, null);
            } else {
                HPLog.e("VPOSActivity", "terminalId null");
            }
            showTransConfirmDialog();
        } else if (action.equals(Do_QueryHXFourElements)) {
            // 转出卡实名认证 是否已保存过四要素 0：无，1有
            status = String.valueOf(luaTable.rawget("status"));
            Double d = Double.parseDouble(status);
            idNum = String.valueOf(luaTable.rawget("idNum"));
            mobileNum = String.valueOf(luaTable.rawget("mobileNum"));
            userName = String.valueOf(luaTable.rawget("userName"));
            if (0 == d.intValue()) {
                HPLog.i(HPLog.FDL_TAG, "--------转出卡实名认证 是否已保存过四要素--------");
                HPLog.i(HPLog.SSX_TAG, mTransferInAccount.toString());
                Intent it = new Intent(this, RealNameAuthentication.class);
                it.putExtra(RealNameAuthentication.TerminlId, mTerminalId);
                BigDecimal bd = new BigDecimal(total);
                String strTotal = bd.toString();
                it.putExtra(RealNameAuthentication.TOTAL, strTotal);
                it.putExtra(RealNameAuthentication.EncryAmt, mEncAmount);
                it.putExtra(RealNameAuthentication.ChannelOrderCurrency, mChannelOrderCurrency);
                it.putExtra(RealNameAuthentication.EncryCurrency, mEncryCurrency);
                it.putExtra(RealNameAuthentication.AccountNumber1, mAccount);
                it.putExtra(RealNameAuthentication.Pan, mPin);
                it.putExtra(RealNameAuthentication.Track2Data, mTrack2);
                it.putExtra(RealNameAuthentication.DynamicKeyData, mDyKey);
                it.putExtra(RealNameAuthentication.AccountNumber2, mEncEncryAccountNum2);
                it.putExtra(RealNameAuthentication.OUT_CARD_NO, mPlainAccount);
                it.putExtra(RealNameAuthentication.OUT_AMOUNT, new BigDecimal(amount).toString());
                it.putExtra(RealNameAuthentication.HP_encData, HPencData);
                it.putExtra(RealNameAuthentication.TransferInAccount, mTransferInAccount.getCardPlainNo());
                it.putExtra(RealNameAuthentication.DCDATA, mDCData);
                it.putExtra(RealNameAuthentication.ICNUM, mICNum);
                it.putExtra(TradingResults.KEY_NAME, mTransferInAccount.getCardName());
                // 新版2.0 添加IC卡有效期：
                it.putExtra(RealNameAuthentication.ExpireDate, mexpireDate);
                it.putExtra(ACTION, this.mAction);
                this.startActivity(it);
                finish();

            } else if (1 == d.intValue()) {
                String address = (String) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_ADDRESS);
                if (!TextUtils.isEmpty(address)) {
                    this.superTransfer(HPencData);
                } else {
                    getCurrentLocation();
                }
            }
        } else if (DO_AccountTransfer.equals(action) || action.equals(DO_AccountTransfer20) || Do_SubatmTransfer.equals(action) || action.equals(DO_MarketAccountTransfer)) {
            boolean isError = false;
            Bill.APPCODE appCode;
            if (DO_AccountTransfer.equals(action) || action.equals(DO_AccountTransfer20)) {
                appCode = Bill.APPCODE.TRANS;
            } else if (action.equals(DO_MarketAccountTransfer)) {
                appCode = Bill.APPCODE.MARKET_TRANS;
            } else {
                appCode = Bill.APPCODE.SUPER_TRANS;
            }
            Bill bill = CommonUtils.generateBill(luaTable, appCode);
            HPLog.i(HPLog.SSX_TAG, bill.toString());
            bill.setTradeType(Bill.TRAD_TYPE_POSPAY);
            Intent intent = new Intent();
            intent.putExtra(ACTION, this.mAction);
            if (Bill.APPCODE.TRANS == appCode || Bill.APPCODE.MARKET_TRANS == appCode) {
                //收款交易消费卡信息采集 成功之后才操作
                if (!TextUtils.isEmpty(bill.getCardNoOutFull()) && !TextUtils.isEmpty(bill.getTransSN()) && !TextUtils.isEmpty(bill.getMerchantCode())) {
                    upLoadBankCardPic(fileUrl, bill.getCardNoOutFull(), bill.getTransTime(), bill.getTransSN(), bill.getMerchantCode(), cardImageNumber, false, false);
                }
                if (Bill.STATUS_SUCCESS == bill.getStatus()) {
                    intent.setClass(this, TransResultSuccessActivity.class);
                    if (TextUtils.isEmpty(bill.getTerminalNo())) {
                        bill.setTerminalNo(getCSN());
                    }
                } else {
                    HPLog.i(HPLog.YL_TAG, "收款交易失败");
                    intent.setClass(this, TransResultFailureActivity.class);
                }
            } else {
                if (bill.getStatus() == Bill.STATUS_FAILED) {
                    byte action_from = this.getIntent().getByteExtra(ZZTongActivity.ACTION_FROM, (byte) 0);
                    if (action_from == ZZTongActivity.Action_FROM_CREDIT) {
                        intent.putExtra(ZZTongActivity.ACTION_FROM, ZZTongActivity.Action_FROM_CREDIT);
                    }
                    intent.setClass(this, TradingResultsFailed.class);
                } else {
                    if (this.mAction == ZZTongActivity.Action_SuperUniTrans) {
                        byte action_from = this.getIntent().getByteExtra(ZZTongActivity.ACTION_FROM, (byte) 0);
                        if (action_from == ZZTongActivity.Action_FROM_CREDIT) {
                            intent.putExtra(ZZTongActivity.ACTION_FROM, ZZTongActivity.Action_FROM_CREDIT);
                        }
                    }
                    intent.setClass(this, TradingResults.class);
                }
                if (mTransferInAccount != null) {
                    intent.putExtra(TradingResults.KEY_NAME, mTransferInAccount.getCardName());
                } else {
                    isError = true;
                }
            }
            if (isError) {
                dealError();
            } else {
                intent.putExtra(ACTION, this.mAction);
                intent.putExtra(QueryBillsActivity.billvalue, bill);
                if (action.equals(ZZTongActivity.DO_MarketAccountTransfer)) {
                    String pageUrl = (String) luaTable.rawget("pageUrl");
//                    HPLog.i(HPLog.YL_TAG, "pageUrl:" + pageUrl);
                    intent.putExtra("pageUrl", SecureManager.getInstance().des(pageUrl, 0, null));
                }
                startActivity(intent);
                onClick(null);
            }
        } else if (Do_GetBusinessControlSwitch.equals(action)) {
            this.closeProgressDialog();
            if (luaTable != null) {
                LuaTable list = (LuaTable) luaTable.rawget("list");
                Vector<LuaTable> dataList = LuaTableUtil.getArray(list);
                // switchType 开关类型 0:刷卡收款四要素,1：转出卡拍照
                // isOpen 开关是否打开状态 1:表示打开,0:表示关闭
                Map<Integer, Integer> maps = new HashMap<Integer, Integer>();
                if (list != null) {
                    for (LuaTable item : dataList) {
                        int switchType = ((Double) item.rawget("switchType")).intValue();
                        int isOpen = ((Double) item.rawget("isOpen")).intValue();
                        maps.put(switchType, isOpen);
                    }
                    iIsOpenFourElements = getMapKeyToValue(maps, 0);
                    iOriginIsOpenFourElements = getMapKeyToValue(maps, 0);
                    iIsOpenNeedCamera = getMapKeyToValue(maps, 1);
                    iOriginIsOpenNeedCamera = getMapKeyToValue(maps, 1);
                    isUinPayOpenFourElements = getMapKeyToValue(maps, 5);
                    if (iOriginIsOpenNeedCamera == 1) {
                        iIsOpenCardScanCamera = getMapKeyToValue(maps, 4);
                        if (iIsOpenCardScanCamera == 1) {
                            iOriginIsOpenCardScanCamera = getMapKeyToValue(maps, 4);
                            iIsOpenNeedCamera = 0;
                        }
                    }
                }
            }
            HPLog.i(HPLog.YL_TAG, "Do_GetBusinessControlSwitch IsOpenFourElements：" + iIsOpenFourElements + "IsOpenNeedCamera：" + iIsOpenNeedCamera + "isUinPayOpenFourElements:" + isUinPayOpenFourElements);
            doCheckBusinessControlSwitch();
        } else if (Do_CheckSwipeCardFourElements.equals(action)) {
            Log.i(HPLog.YL_TAG, "------------Do_CheckSwipeCardFourElements---------------");
            int responseCode = CommonUtils.objectToInt(luaTable.rawget("responseCode"));
            if (responseCode != 0) {
                String errMessage = CommonUtils.objectToString(luaTable.rawget("errMessage"));
                showAlertDialog(this, getString(R.string.tip), errMessage);
            } else {
                String status = (String) luaTable.rawget("status");
                if (status.equals("1")) {
                    // doPreNext();
                    iIsOpenFourElements = 0;
                    isUinPayOpenFourElements = 0;
                    doCheckBusinessControlSwitch();
                } else if (status.equals("0")) {
                    Intent intent = new Intent();
                    if (this.mAction == ZZTongActivity.Action_SuperUniTrans) {
                        Bill bill = new Bill();
                        String transSN = (String) luaTable.rawget("transSN");
                        String cardNoOut = (String) luaTable.rawget("cardNo");
                        String transTime = (String) luaTable.rawget("transTime");
                        String transStatus = (String) luaTable.rawget("message");
                        bill.setTradeType(Bill.TRAD_SUPER_UNIPAY);
                        bill.setCardNoOut(CommonUtils.formattingCard_4(cardNoOut));
                        bill.setCardNoIn(CommonUtils.formattingCard_4(mTransferInAccount.getCardPlainNo()));
                        bill.setTransTime(transTime);
                        bill.setTransSN(transSN);
                        bill.setTransChannel("2");
                        bill.setTransStatus(transStatus);
                        intent.setClass(this, TradingResultsFailed.class);
                        intent.putExtra(TradingResultsFailed.KEY_NAME, mTransferInAccount.getCardPlainNo());
                        intent.putExtra(ACTION, this.mAction);
                        HPLog.i(HPLog.SSX_TAG, bill.toString());
                        byte action_from = this.getIntent().getByteExtra(ZZTongActivity.ACTION_FROM, (byte) 0);
                        if (action_from == ZZTongActivity.Action_FROM_CREDIT) {
                            intent.putExtra(ACTION_FROM, action_from);
                        }
                        intent.setClass(this, TradingResultsFailed.class);
                        intent.putExtra(QueryBillsActivity.billvalue, bill);
                    } else {
                        intent.setClass(this, TransResultFourElementsFailureActivity.class);
                        Bill bill = new Bill();
                        bill.setAppcode(Bill.APPCODE.TRANS);
                        bill.setStatus(Integer.valueOf(status).intValue());
                        bill.setCardNoOut(CommonUtils.formattingCard_4((String) luaTable.rawget("cardNo")));
                        bill.setTransTime((String) luaTable.rawget("transTime"));
                        bill.setTransSN((String) luaTable.rawget("transSN"));
                        bill.setTransStatus((String) luaTable.rawget("message"));
                        bill.setAmount(total);
                        intent.putExtra(QueryBillsActivity.billvalue, bill);
                    }
                    startActivity(intent);
                    goBack();
                }
            }
        }
        return true;
    }

    public int getMapKeyToValue(Map<Integer, Integer> map, int key) {
        try {
            Integer format = map.get(key);
            if (null != format) {
                return format.intValue();
            }
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("result", "requestCode:" + requestCode);
        if (requestCode == ZZTConstant.REQUEST_CAMERA_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                // 保存成功
                if (data != null && data.getStringExtra("FileUrl") != null) {
                    fileUrl = data.getStringExtra("FileUrl");
                    if (mDialog != null){
                        mDialog.dismiss();
                    }
                }
                iIsOpenNeedCamera = 0;
                doCheckBusinessControlSwitch();
                HPLog.i(HPLog.YL_TAG, "onActivityResult--保存成功 ");
            } else {
                // 保存失败
                HPLog.i(HPLog.YL_TAG, "onActivityResult--保存失败");
            }
        }
        if (requestCode == isCardRequestCode) {
            if (resultCode == RESULT_OK && data != null) {
                Log.i("result", "resultCode == RESULT_OK && data != null");
                long time = data.getLongExtra(ISCardScanActivity.EXTRA_KEY_TIME, 0);
                ResultData result = (ResultData) data.getSerializableExtra(ISCardScanActivity.EXTRA_KEY_RESULT);
                // 卡号
                String cardNumber = result.getCardNumber();

                // 截取后的图片
                Bitmap bigBmp = BitmapFactory.decodeFile(BitmapUtil.trimed_card_img);

                HPLog.e("isCCCard", "时间：" + time + "ms");
                HPLog.e("isCCCard", "卡号：" + cardNumber);
                HPLog.e("isCCCard", "截取后的拍照图片是否有值：" + bigBmp);
                if (!TextUtils.isEmpty(cardNumber) && bigBmp != null) {
                    fileUrl = BitmapUtil.trimed_card_img;
                    cardImageNumber = cardNumber;
                    iIsOpenNeedCamera = 0;
                    if (mDialog != null){
                        mDialog.dismiss();
                    }
                } else {
                    iIsOpenNeedCamera = 1;
                }
            } else {
                iIsOpenNeedCamera = 1;
                iIsOpenCardScanCamera = 0;
                fileUrl = null;
                cardImageNumber = null;
                HPLog.e("isCCCard", "返回失败。。。 未拍照");
            }
            Log.i("result", "cardNumber:" + cardImageNumber);
            doCheckBusinessControlSwitch();
        }

    }

    /***
     * 业务控制开关 iIsOpenCardScanCamera 是否调用SDK拍照
     */
    private void doCheckBusinessControlSwitch() {
        //银联转账不需要拍照功能
        if (mAction == Action_SuperUniTrans) {
            if (isUinPayOpenFourElements == 1) {
                refreshStatus(ISwiperListener.Status_Four_Elements);
                return;
            }
        } else {
            HPLog.i("tag-iIsOpenCardScanCamera", iIsOpenCardScanCamera + "");
            HPLog.i("tag-iIsOpenNeedCamera", iIsOpenNeedCamera + "");
            //是否拍照
            if (iIsOpenNeedCamera == 1) {
                if (iOriginIsOpenCardScanCamera == 1 && iIsOpenCardScanCamera == 0) {
                    openCustomCameraActivity();
                } else {
                    showTipCamera(true);
                }
                return;
            }
            HPLog.i("result", "iIsOpenFourElements:" + iIsOpenFourElements);
            if (iIsOpenFourElements == 1) {
                refreshStatus(ISwiperListener.Status_Four_Elements);
                return;
            }
        }
        doPreNext();
    }

    private void openBankCardScanningActivity() {
        HPLog.i("tag-----", "自定义拍照界面");
        if (useScanType == 0) {
            try {
                Intent intent = new Intent(this, ISCardScanActivity.class);
                // 指定SDK相机模块ISCardScanActivity四边框角线条,检测到银行卡图片后的颜色
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_COLOR_MATCH, 0xffff0000);
                // 指定SDK相机模块ISCardScanActivity四边框角线条颜色，正常显示颜色
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_COLOR_NORMAL, 0xff00ff00);
                // 指定SDK相机模块ISCardScanActivity提示字符串
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_TIPS, "请将银行卡放在框内识别");
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_ORIENTATION, ISCardScanActivity.ORIENTATION_VERTICAL);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_GET_NUMBER_IMG, false);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_GET_TRIMED_IMG, BitmapUtil.trimed_card_img);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_GET_ORIGINAL_IMG, BitmapUtil.origianl_card_img);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_APP_KEY, BaseProtocolKey.KEY_CC_CARD);
                HPLog.e("isCCCard", "KEYS=" + BaseProtocolKey.KEY_CC_CARD);
                startActivityForResult(intent, isCardRequestCode);
            } catch (Exception e) {
                HPLog.e("isCCCard", "出错了");
                e.printStackTrace();
            }
        } else if (useScanType == 1) {
            try {
                Intent intent = new Intent(this, PreviewActivity.class);
                // 指定SDK相机模块ISCardScanActivity四边框角线条,检测到银行卡图片后的颜色
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_COLOR_MATCH, 0xffff0000);
                // 指定SDK相机模块ISCardScanActivity四边框角线条颜色，正常显示颜色
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_COLOR_NORMAL, 0xff00ff00);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_ORIENTATION, ISCardScanActivity.ORIENTATION_VERTICAL);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_GET_NUMBER_IMG, false);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_GET_TRIMED_IMG, BitmapUtil.trimed_card_img);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_GET_ORIGINAL_IMG, BitmapUtil.origianl_card_img);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_APP_KEY, BaseProtocolKey.KEY_CC_CARD);
                startActivityForResult(intent, isCardRequestCode);
            } catch (Exception e) {
                HPLog.e("isCCCard", "出错了");
                e.printStackTrace();
            }
        }
    }



    public void showTipCamera(boolean isShowDialog) {
        if (isShowDialog) {
            mDialog = new ZZTShowDialog(this, R.layout.dialog, R.style.dialog);
            mDialog.setDialogCallback(new ZZTShowDialog.Dialogcallback() {
                @Override
                public void ButtonOk() {
                    if (SystemClock.elapsedRealtime() - mLastClickTime < 2000) {
                        return;
                    }
                    mLastClickTime = SystemClock.elapsedRealtime();
                    if (iOriginIsOpenCardScanCamera == 1) {
                        openBankCardScanningActivity();
                    } else {
                        openCustomCameraActivity();
                    }
                }

                @Override
                public void ButtonCancel() {
                    iIsOpenNeedCamera = 0;
                    doCheckBusinessControlSwitch();
                }
            });
            mDialog.show();
        } else {
            openCustomCameraActivity();
        }
    }

    /**
     * 打开对话框
     */
    private void openCustomCameraActivity() {
        Intent cIntent = new Intent(VPOSActivity.this, CameraCardPhotoActivity.class);
        VPOSActivity.this.startActivityForResult(cIntent, ZZTConstant.REQUEST_CAMERA_CODE);
    }

    /***
     * 确认交易框提示
     */
    private void showTransConfirmDialog() {
        LayoutInflater li = LayoutInflater.from(this);
        final View content = li.inflate(R.layout.super_transfer_confirm, null);
        AlertDialog.Builder ab = new AlertDialog.Builder(this);
        final AlertDialog dialog = ab.create();
        // 清除黑色背景
        dialog.setView(content, 0, 0, 0, 0);
        dialog.setCancelable(false);
        content.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @SuppressWarnings("deprecation")
            @Override
            public void onGlobalLayout() {
                ViewGroup temp = (ViewGroup) content;
                while (null != temp) {
                    // 从内容往上decorView设置，所有的View为透明
                    if (temp.getParent() instanceof ViewGroup) {
                        temp = (ViewGroup) temp.getParent();
                    } else {
                        break;
                    }
                    ColorDrawable cd = new ColorDrawable();
                    // cd.setColor(Color.TRANSPARENT);
                    cd.setAlpha(0);
                    temp.setBackgroundDrawable(cd);
                    temp.setBackgroundColor(Color.TRANSPARENT);
                }
                WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
                lp.copyFrom(dialog.getWindow().getAttributes());
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                lp.gravity = Gravity.CENTER;
                dialog.getWindow().setAttributes(lp);
                content.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
        TextView repayAmount = (TextView) content.findViewById(R.id.label_amount);
        TextView repayFee = (TextView) content.findViewById(R.id.label_fee);
        if (mAction == ZZTongActivity.Action_CreditCardRepay) {
            repayAmount.setText(R.string.repayment_amount);
            repayFee.setText(R.string.repayment_fee);
        }
        TextView tv = (TextView) content.findViewById(R.id.cardNoInTextView);
        tv.setText(CommonUtils.formattingCard_4(mTransferInAccount.getCardNo()));
        tv = (TextView) content.findViewById(R.id.tvCardInName);
        tv.setText(mTransferInAccount.getCardName());
        tv = (TextView) content.findViewById(R.id.amountTextView);
        tv.setText(CommonUtils.formatMoney(amount / 100));
        tv = (TextView) content.findViewById(R.id.totalTextView);
        tv.setText(CommonUtils.formatMoney(total / 100));
        tv = (TextView) content.findViewById(R.id.feeTextView);
        tv.setText(CommonUtils.formatMoney((total - amount) / 100));
        Button btn = (Button) content.findViewById(R.id.cancelButton);
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                VPOSActivity.this.onClick(null);
            }
        });
        btn = (Button) content.findViewById(R.id.okButton);
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                affirmAmount();
            }
        });
        dialog.setOwnerActivity(this);
        dialog.show();
    }

    @Override
    protected void goBack() {
        if (!this.isFinishing()) {
            clearFactor();
            stopAdpu();
            super.goBack();
        } else {
            HPLog.i("VPOSActivity", "ignore stopApdu");
        }
    }

    @Override
    protected void onDestroy() {
        if (swiperCardView != null) {
            swiperCardView.doDestroy();
            swiperCardView = null;
        }
        super.onDestroy();
    }

    @Override
    public void onSwiperStatus(int status, int result, String pan, boolean isDownlTrd) {
        super.onSwiperStatus(status, result, pan, isDownlTrd);
        HPLog.i("onSwiperStatus status:", status + " : result" + result + ":pan " + pan + " mAction:" + mAction);
        if (result == ISwiperListener.Swiper_OK) {
            if (isDownlTrd && !ZZTConfig.DW_TRADE) {
                showAlertDialog(this, getString(R.string.tip), getString(R.string.downgrade_trading_toast), false, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        doSwipe();
                    }
                }, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        VPOSActivity.this.onClick(null);
                    }
                });
                return;
            }
            switch (mAction) {
                // 什么时候会走到这里面?
                case Action_Register:// 开通，加密PIN
                case Action_AddAccount:// 绑卡，加密PIN
                    if (status == ISwiperListener.Status_EncyptData) {
                        refreshStatus(ISwiperListener.Status_Swipe);
                        SwiperTemp = true;
                    } else if (status == ISwiperListener.Status_Swipe) {
                        refreshStatus(ISwiperListener.Status_InputPwdRegister);
                    } else if (status == ISwiperListener.Status_InputPwdRegister) {
                        refreshStatus(ISwiperListener.Status_MAC);
                    }
                    break;
                case Action_Transfer1:// 转账1（选卡确认金额）
                case Action_Transfer2:// 转账2（发起转账请求）
                case Action_SameTransfer1:// 同名转账1（选卡确认金额）
                case Action_SameTransfer2:// 同名转账2（发起转账请求）
                case Action_MARKET:// 分销系统
                    this.mPlainAccount = pan;
                    if (status == ISwiperListener.Status_AffirmAmount) {
                        if (ApiSwiperFactory.getInstance().isSupportAffirmAmount()) {
                            refreshStatus(ISwiperListener.Status_Swipe);
                            SwiperTemp = true;
                        }
                    } else if (status == ISwiperListener.Status_Swipe) {
                        HPLog.e(HPLog.FDL_TAG, "mPlainAccount:" + mPlainAccount);
                        if (TextUtils.isEmpty(mPlainAccount)) {
                            HPLog.e(HPLog.FDL_TAG, "Status_Swipe-----------mPlainAccount is null");
                            showAlertDialog(this, getString(R.string.tip), getString(R.string.card_no_response), false, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    refreshStatus(ISwiperListener.Status_Swipe);
                                    doSwipe();
                                    dialog.dismiss();
                                }
                            }, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    VPOSActivity.this.onClick(null);
                                }
                            });
                        }
                        showPwd();
                    } else if (status == ISwiperListener.Status_InputPwdRegister) {
                        // 六期不应该存在Status_InputPwdRegister，不会走到这里
                        refreshStatus(ISwiperListener.Status_MAC);
                    }
                    break;
                case Action_BalanceEnquiry:// 余额查询
                    if (status == ISwiperListener.Status_Swipe) {
                        showPwd();
                    } else if (status == ISwiperListener.Status_InputPwdRegister) {
                        // 六期不应该存在Status_InputPwdRegister，不会走到这里
                        refreshStatus(ISwiperListener.Status_MAC);
                    }
                    break;
                case Action_Phone:
                case Action_Qb:
                case Action_Game:
                    if (status == ISwiperListener.Status_Swipe) {
                        showPwd();
                    } else if (status == ISwiperListener.Status_InputPwdTrade) {
                        refreshStatus(ISwiperListener.Status_EncyptData);
                    }
                    break;
                case Action_SuperTransfer:
                case Action_CreditCardRepay: { // 超级转账
                    if (ISwiperListener.Status_Swipe == status) {
                        HPLog.i("VPOSActivity", "super trans: stauts_swipe");
                        this.mPlainAccount = pan;
                        Double latitude = (Double) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_LATITUDE, 0d);
                        Double longtitude = (Double) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_LONGTITUDE, 0d);
                        String address = (String) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_ADDRESS);
                        Hashtable<String, String> params = new Hashtable<String, String>();
                        params.put("accountType", "K");
                        params.put("amount", SecureManager.getInstance().des(amount + "", 1, null));
                        params.put("inCardNo", SecureManager.getInstance().des(pan, 1, null));
                        params.put("outCardNo", SecureManager.getInstance().des(mTransferInAccount.getCardPlainNo(), 1, null));
                        String csn = SwiperUtils.getCsn();
                        params.put("csn", SecureManager.getInstance().des(csn, 1, null));
                        params.put("channel", ClientEngine.CHANNEL);
                        params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountName(this), 1, null));
                        params.put(BaseProtocolKey.KEY_LOCATION, latitude.toString() + "," + longtitude.toString());
                        params.put(BaseProtocolKey.KEY_ADDRESS, address);
                        doPost(this, Do_SubatmQueryFee, params);
                    } else if (ISwiperListener.Status_AffirmAmount == status) {
                        showPwd();
                    }
                    break;
                }
                case Action_SuperUniTrans:
                    if (ISwiperListener.Status_Swipe == status) {
                        total = amount;
                        affirmAmount();
                    } else if (ISwiperListener.Status_AffirmAmount == status) {
                        showPwd();
                    }
                    break;
            }
        } else if (ISwiperListener.Swiper_Cancel == result) {
            Toast.makeText(this, R.string.user_cancel, Toast.LENGTH_LONG).show();
            goBack();
        }
        if (ISwiperListener.Swiper_Timeout == result || ISwiperListener.Swiper_Error == result) {
            switch (mAction) {
                case Action_Transfer1:// 转账1（选卡确认金额）
                case Action_Transfer2:// 转账2（发起转账请求）
                case Action_SameTransfer1:// 同名转账1（选卡确认金额）
                case Action_SameTransfer2:// 同名转账2（发起转账请求）
                case Action_SuperTransfer:// 超级转账
                case Action_CreditCardRepay:// 信用卡还款
                case Action_BalanceEnquiry:// 余额查询
                case Action_Phone:
                case Action_Qb:
                case Action_Game:
                    // 刷卡器没好，停止。避免stackoverflow.测试的时候可能会走到这里,刷卡器异常 如果当前刷卡超时后马上关闭刷卡器也会走这个地方
                    if (!SwiperUtils.isSwiperConnected() || !SwiperUtils.isSwiperOK()) {
                        HPLog.i("VPOSActivity", "unplug device");
                        return;
                    }
                    // 当刷卡、确认金额、输入密码等步骤出现错误或超时的时候，重新发消息
                    if (status == ISwiperListener.Status_Swipe) {
                        // 不能把这行代码换成refreshStatus(InterfaceSwiper.Status_Swipe);
                        // doSwipe();
                        showAlertDialog(this, getString(R.string.tip), getString(R.string.card_no_response), false, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                if (SwiperUtils.isSwiperConnected()) {
                                    refreshStatus(ISwiperListener.Status_Swipe);
                                    doSwipe();
                                } else {
                                    Toast.makeText(VPOSActivity.this, VPOSActivity.this.getString(R.string.device_failed), Toast.LENGTH_LONG).show();
                                    goBack();
                                }
                            }
                        }, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                VPOSActivity.this.onClick(null);
                            }
                        });
                    } else if (status == ISwiperListener.Status_AffirmAmount) {
                        // Toast.makeText(this, R.string.affirm_timeout_error,
                        // Toast.LENGTH_SHORT).show();
                        // affirmAmount();
                        showAlertDialog(this, getString(R.string.tip), getString(R.string.affirm_timeout_error), false, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                affirmAmount();
                            }
                        }, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                VPOSActivity.this.onClick(null);
                            }
                        });
                    } else if (status == ISwiperListener.Status_InputPwdTrade) {
                        // Toast.makeText(this,
                        // R.string.input_password_timeout_error,
                        // Toast.LENGTH_SHORT).show();
                        showAlertDialog(this, getString(R.string.tip), getString(R.string.input_password_timeout_error), false, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                if (SwiperUtils.isSwiperConnected()) {
                                    doInputPwd();
                                } else {
                                    Toast.makeText(VPOSActivity.this, VPOSActivity.this.getString(R.string.device_failed), Toast.LENGTH_LONG).show();
                                    goBack();
                                }
                            }
                        }, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                VPOSActivity.this.onClick(null);
                            }
                        });
                    }
            }
        }
    }

    @Override
    public void onSwiperStatus(int status, int result, String keyIndex, String encData, String plainData) {
        HPLog.d("VPOSActivity", "onSwiperStatus result :" + result + " encData:" + encData + " plainData:" + plainData + " keyIndex:" + keyIndex);
        if (ISwiperListener.Status_EncyptData == status) {
            if (ISwiperListener.Swiper_OK == result && !TextUtils.isEmpty(encData)) {
                // 加密 terminalId---加密币种channelOrderCurrency----
                if (ZZTongActivity.Action_SuperTransfer == mAction || ZZTongActivity.Action_CreditCardRepay == mAction) {
                    String toEncry = null;
                    if (plainData.equals(mTerminalId)) {
                        mTerminalId = encData;
                        // 加密terminalId
                        toEncry = mChannelOrderCurrency;
                        doEncryData(toEncry);
                    } else if (plainData.equals(mChannelOrderCurrency)) {
                        mEncryCurrency = encData;
                        // 加密12位的金额明文
                        toEncry = CommonUtils.formatMoneyToPos(total, UPConfig.SUPER_TRANS_AMOUNT_LEN);
                        doEncryData(toEncry);
                    } else if (plainData.equals(CommonUtils.formatMoneyToPos(total, UPConfig.SUPER_TRANS_AMOUNT_LEN))) {
                        mEncAmount = encData;
                        // 加密转入卡号
                        toEncry = mTransferInAccount.getCardPlainNo();
                        doEncryData(toEncry);
                    } else if (null != mTransferInAccount && plainData.equals(mTransferInAccount.getCardPlainNo())) {
                        mEncEncryAccountNum2 = encData;
                        // 拼出terminalId
                        // +" "+encryAmt+" "+encryCurrency+" "+accountNumber1+" "+pan+" "+track2Data+" "+accountNumber2+" "+cardSerialNumber+" "+dynamicKeyData
                        // 然后用刷卡器加密
                        StringBuilder sb = new StringBuilder(150);
                        String time = getFactorTime();
                        sb.append(time);
                        sb.append(" ");
                        sb.append(mTerminalId);
                        sb.append(" ");
                        sb.append(mEncAmount);
                        sb.append(" ");
                        sb.append(mEncryCurrency);
                        sb.append(" ");
                        sb.append(mAccount);
                        if (!TextUtils.isEmpty(mTrack2)) {
                            sb.append(" ");
                            sb.append(mTrack2);
                        }
                        sb.append(" ");
                        sb.append(SwiperUtils.getCsn());
                        sb.append(" ");
                        sb.append(mEncEncryAccountNum2);
                        if (!TextUtils.isEmpty(mICNum)) {
                            sb.append(" ");
                            sb.append(mICNum);
                        }
                        if (!TextUtils.isEmpty(mDCData)) {
                            sb.append(" ");
                            sb.append(mDCData);
                        }
                        // 做Mac校验
                        toEncry = sb.toString();
                        doMac(toEncry);
                    } else {
                        if (ISwiperListener.MacDataIndex.equals(keyIndex)) {
                            HPencData = encData;
                            TransferCardAuthentication();
                        } else {
                            // 出现错误!返回主界面。
                            HPLog.e("VPOSActivity", "encry data logic error!");
                            goBack();
                        }
                    }
                } else if (ZZTongActivity.Action_SuperUniTrans == mAction) {
                    String toEncry = null;
                    if (plainData.equals(mTerminalId)) {
                        mTerminalId = encData;
                        // 加密terminalId
                        toEncry = mChannelOrderCurrency;
                        doEncryData(toEncry);
                    } else if (plainData.equals(mChannelOrderCurrency)) {
                        mEncryCurrency = encData;
                        // 加密12位的金额明文
                        toEncry = CommonUtils.formatMoneyToPos(total, UPConfig.SUPER_TRANS_AMOUNT_LEN);
                        doEncryData(toEncry);
                    } else if (plainData.equals(CommonUtils.formatMoneyToPos(total, UPConfig.SUPER_TRANS_AMOUNT_LEN))) {
                        mEncAmount = encData;
                        // 加密转入卡号
                        toEncry = mTransferInAccount.getCardPlainNo();
                        doEncryData(toEncry);
                    } else if (null != mTransferInAccount && plainData.equals(mTransferInAccount.getCardPlainNo())) {
                        mEncEncryAccountNum2 = encData;
                        // 拼出terminalId
                        // +" "+encryAmt+" "+encryCurrency+" "+accountNumber1+" "+pan+" "+track2Data+" "+accountNumber2+" "+cardSerialNumber+" "+dynamicKeyData
                        // 然后用刷卡器加密
                        StringBuilder sb = new StringBuilder(150);
                        String time = getFactorTime();
                        sb.append(time);
                        sb.append(" ");
                        sb.append(mTerminalId);
                        sb.append(" ");
                        sb.append(mEncAmount);
                        sb.append(" ");
                        sb.append(mEncryCurrency);
                        sb.append(" ");
                        sb.append(mAccount);
                        if (!TextUtils.isEmpty(mTrack2)) {
                            sb.append(" ");
                            sb.append(mTrack2);
                        }
                        sb.append(" ");
                        sb.append(SwiperUtils.getCsn());
                        sb.append(" ");
                        sb.append(mEncEncryAccountNum2);
                        if (!TextUtils.isEmpty(mICNum)) {
                            sb.append(" ");
                            sb.append(mICNum);
                        }
                        if (!TextUtils.isEmpty(mDCData)) {
                            sb.append(" ");
                            sb.append(mDCData);
                        }
                        // 做Mac校验
                        toEncry = sb.toString();
                        doMac(toEncry);
                    } else {
                        if (ISwiperListener.MacDataIndex.equals(keyIndex)) {
                            HPencData = encData;
                            //如果是银联转账则直接 调用转账接口，不需要调用瀚兴四要素验证
                            this.superTransfer(HPencData);
                        } else {
                            // 出现错误!返回主界面。
                            HPLog.e("VPOSActivity", "encry data logic error!");
                            goBack();
                        }
                    }
                } else if (ZZTongActivity.Action_BalanceEnquiry == mAction) {
                    if (ZZTConfig.ENV.BALANCE_ENQUIRE_UP) {
                        if (ISwiperListener.MacDataIndex.equals(keyIndex)) {
                            String xml = UPXMLReqComposer.xmlBalanceReq(getFactor().substring(0, 14), mAccount, mPin, mTrack2, getCSN(), mDyKey, encData);
                            HttpSFTConnector.doPostUrl(this, UPConfig.UPHost, xml, true);
                        }
                    }
                }
            }
        }
        // 必须调用父类，父类处理加密失败，重试的操作。
        super.onSwiperStatus(status, result, keyIndex, encData, plainData);
    }

    @Override
    public void onSwiperStatus(int status, int result, HashMap<String, String> hmData) {
        HPLog.i("VPOSActivity", "onSwiperStatus hmData. status:" + status + "mAction:" + mAction);
        if (ISwiperListener.Swiper_OK == result && ISwiperListener.Status_InputPwdTrade == status) {
            mBankInfoHashMap = hmData;
            HPLog.i("VPOSActivity", "onSwiperStatus:" + mBankInfoHashMap.toString());
            String plainAccount = mBankInfoHashMap.get(IBusinessSwiper.BANK_PLAIN_ACCOUNT_KEY);
            String expireDate = mBankInfoHashMap.get(IBusinessSwiper.BANK_PLAIN_EXPIRE_DATE);
            if (mAction == ZZTongActivity.Action_Transfer1 || mAction == ZZTongActivity.Action_MARKET) {
                getBusinessControlSwitch(plainAccount, expireDate);
            } else if (ZZTongActivity.Action_SuperUniTrans == mAction) {
                //银联转账需要获取是否需要检查 四要素
                getBusinessControlSwitchForUniPay(plainAccount, expireDate);
            } else {
                doPreNext();
            }
        } else if (ISwiperListener.Swiper_OK == result && ISwiperListener.Status_Swipe == status) {
            // 刷卡后，获得了卡号。
            String plainAccount = hmData.get(IBusinessSwiper.BANK_PLAIN_ACCOUNT_KEY);
            HPLog.i("VPOSActivity", "plainAccount:" + plainAccount);
            this.mPlainAccount = plainAccount;
            if (ZZTongActivity.Action_SuperTransfer == mAction || ZZTongActivity.Action_CreditCardRepay == mAction) {
                Double latitude = (Double) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_LATITUDE, 0d);
                Double longtitude = (Double) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_LONGTITUDE, 0d);
                String address = (String) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_ADDRESS);
                Hashtable<String, String> params = new Hashtable<String, String>();
                params.put("accountType", "K");
                HPLog.i(HPLog.SSX_TAG, "加密前金额：" + amount);
                params.put("amount", SecureManager.getInstance().des(amount + "", 1, null));
                HPLog.i(HPLog.SSX_TAG, "加密后金额：" + SecureManager.getInstance().des(amount + "", 1, null));
                HPLog.i(HPLog.SSX_TAG, "解密后金额：" + SecureManager.getInstance().des(amount + "", 0, null));
                params.put("inCardNo", SecureManager.getInstance().des(plainAccount, 1, null));
                params.put("outCardNo", SecureManager.getInstance().des(mTransferInAccount.getCardPlainNo(), 1, null));
                String csn = SwiperUtils.getCsn();
                params.put("csn", SecureManager.getInstance().des(csn, 1, null));
                params.put("channel", ClientEngine.CHANNEL);
                params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountName(this), 1, null));
                params.put(BaseProtocolKey.KEY_LOCATION, latitude.toString() + "," + longtitude.toString());
                params.put(BaseProtocolKey.KEY_ADDRESS, address);
                doJsonPost(this, Do_SubatmQueryFee, MicroSuperFeeBean.class, params);
            } else if (ZZTongActivity.Action_SuperUniTrans == mAction) {
                total = amount;
                affirmAmount();
            } else if (ZZTongActivity.Action_Transfer1 == mAction || ZZTongActivity.Action_Transfer2 == mAction || ZZTongActivity.Action_SameTransfer1 == mAction || ZZTongActivity.Action_SameTransfer2 == mAction || ZZTongActivity.Action_BalanceEnquiry == mAction) {
                // 通知界面去更新
                if (TextUtils.isEmpty(plainAccount)) {
                    HPLog.e(HPLog.FDL_TAG, "Status_Swipe-----------mPlainAccount is null");
                    showAlertDialog(this, getString(R.string.tip), getString(R.string.card_no_response), false, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            refreshStatus(ISwiperListener.Status_Swipe);
                            doSwipe();
                            dialog.dismiss();
                        }
                    }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            VPOSActivity.this.onClick(null);
                        }
                    });
                }
                showPwd();
            }
        } else if (ISwiperListener.Swiper_Error == result && ISwiperListener.Status_InputPwdTrade == status) {
            //2017/7/25-这里在onActivityResult显示以后每页关闭，导致这里显示时异常
            closeProgressDialog();
            // 获取出现错误。退出当前界面，重新来。
            this.showAlertDialog(this, getString(R.string.tip), getString(R.string.warning_ency_failed), false, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    closeAlertDialog();
                    VPOSActivity.this.onClick(null);
                }
            });
        }
        super.onSwiperStatus(status, result, hmData);
    }

    public void doCheckSwipeCardFourElements(String bank_no, String name, String id_no, String mobile_no) {
        HPLog.e(HPLog.YL_TAG, "Do_CheckSwipeCardFourElements Post");
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("name", SecureManager.getInstance().des(name, 1, null));
        params.put("phone", SecureManager.getInstance().des(mobile_no, 1, null));
        params.put("cardNo", SecureManager.getInstance().des(bank_no, 1, null));
        params.put("certNo", SecureManager.getInstance().des(id_no, 1, null));
        params.put("clientChannel", ZZTConfig.UPDATE_CHANNEL);
        params.put("channel", ClientEngine.CHANNEL);
        doJsonPost(this, ZZTongActivity.Do_CheckSwipeCardFourElements, CheckSwipeCardFourElements.class, params);
    }

    private void getBusinessControlSwitch(String cardNo, String expireDate) {
        Hashtable<String, String> params = new Hashtable<String, String>();
        String accountName = AccountUtils.getAccountName(this);
        params.put("account", SecureManager.getInstance().des(accountName, 1, null));
        params.put("channel", ClientEngine.CHANNEL);
        params.put("clientChannel", ZZTConfig.UPDATE_CHANNEL);
        params.put("cardNo", SecureManager.getInstance().des(cardNo, 1, null));
        if (!TextUtils.isEmpty(expireDate)) {
            params.put("expireDate", SecureManager.getInstance().des(expireDate, 1, null));
        }
        String encAmount = SecureManager.getInstance().des(amount + "", 1, null);
        params.put("amount", encAmount);
        String encCsn = SecureManager.getInstance().des(ApiSwiperFactory.getInstance().getCSN(), 1, null);
        params.put("csn", encCsn);
        doJsonPost(true, this, ZZTongActivity.Do_GetBusinessControlSwitch, BusinessControlSwitch.class, params, true);
    }

    private void getBusinessControlSwitchForUniPay(String cardNo, String expireDate) {
        Hashtable<String, String> params = new Hashtable<String, String>();
        String accountName = AccountUtils.getAccountName(this);
        params.put("account", SecureManager.getInstance().des(accountName, 1, null));
        params.put("channel", ClientEngine.CHANNEL);
        params.put("clientChannel", ZZTConfig.UPDATE_CHANNEL);
        params.put("cardNo", SecureManager.getInstance().des(cardNo, 1, null));
        if (!TextUtils.isEmpty(expireDate)) {
            params.put("expireDate", SecureManager.getInstance().des(expireDate, 1, null));
        }
        String encAmount = SecureManager.getInstance().des(amount + "", 1, null);
        params.put("amount", encAmount);
        String encCsn = SecureManager.getInstance().des(ApiSwiperFactory.getInstance().getCSN(), 1, null);
        params.put("csn", encCsn);
        params.put("switchType", "5");
        doJsonPost(true, this, ZZTongActivity.Do_GetBusinessControlSwitch, BusinessControlSwitch.class, params, true);
    }

    private void doPreNext() {
        HashMap<String, String> hmData = mBankInfoHashMap;
        HPLog.i(HPLog.YL_TAG, "mBankInfoHashMap value:" + mBankInfoHashMap.toString());
        if (null == hmData) {
            HPLog.e("Vpos", "onSwiperStatus hmData isNull");
            dealError();
            return;
        }
        // 输入密码后，getBankInfo返回了
        String account = hmData.get("account");
        String plainAccount = hmData.get(IBusinessSwiper.BANK_PLAIN_ACCOUNT_KEY);
        if (TextUtils.isEmpty(plainAccount) && !TextUtils.isEmpty(this.mPlainAccount)) {
            plainAccount = this.mPlainAccount;
        }
        String pin = hmData.get("pin");
        String encAmount = hmData.get("amount");
        String track2 = hmData.get("track2");
        String track3 = hmData.get("track3");
        // 新版刷卡器需要的内容
        String dcdata = hmData.get(IBusinessSwiper.BANK_DCDATA);
        String icnumber = hmData.get(IBusinessSwiper.BANK_ICNUMBER);
        String mac = hmData.get("mac");
        // 新版刷卡器需要的内容
        String dynamicKeyData = hmData.get("dynamicKeyData");
        String address = (String) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_ADDRESS);

        // 新版 2.0.0 添加IC卡有效期
        String exDate = hmData.get(IBusinessSwiper.BANK_PLAIN_EXPIRE_DATE);
        HPLog.e(HPLog.FDL_TAG, "mac:IC  返回的结果是exDate：" + exDate);
        HPLog.e(HPLog.FDL_TAG, "mac:IC  返回的结果是mac：" + mac);
        HPLog.e(HPLog.FDL_TAG, "mac:IC  返回的结果是dcdata：" + dcdata);
        if (!TextUtils.isEmpty(address)) {
            doNext(account, plainAccount, pin, track2, track3, encAmount, dynamicKeyData, dcdata, icnumber, mac, exDate);
        } else {
            getCurrentLocation();
        }
    }

    private void showPwd() {
        HPLog.i(HPLog.YL_TAG, "showPwd:" + ApiSwiperFactory.getInstance().getSwiperModel());
        HPLog.i(HPLog.TAG_RESULT, "ishowpwd:" + ApiSwiperFactory.getInstance().isSupportInputPwd());
        refreshPwdScreen(!ApiSwiperFactory.getInstance().isSupportInputPwd());
        doInputPwd();
    }

    @Override
    public void onShownPwd() {
        refreshPwdScreen(true);
    }

    @Override
    public void onSwiperStatus(int status, int result, String encPwd) {
        HPLog.d("VPOSActivity", "onSwiperStatus encPwd");
        super.onSwiperStatus(status, result, encPwd);
    }

    public void dealError() {
        showAlertDialog(this, "温馨提示", "刷卡器异常，请重试", false, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                goBack();
            }
        });
    }

    public void stopSwiper() {
        goBack();
    }

    // 发请求，开启线程。
    public class WebService implements Runnable {
        String xml = null;

        public WebService(String xmlFormat1) {
            xml = xmlFormat1;
        }

        @Override
        public void run() {
            String result = new UPConnect(xml, UPConfig.UPHost).execute();
            HPLog.e("resultXml", result);
            ClientEngine.getInstance().saveGlobal(IBusinessSwiper.BANK_TransactionType_KEY, null);// 无论成功或者失败,都清空这个标记
            Bundle data = new Bundle();
            data.putString("result", result);
            Message msg = new Message();
            msg.setData(data);
            h.sendMessage(msg);
        }
    }

    private Handler h = new Handler() {
        public void handleMessage(android.os.Message msg) {
            closeProgressDialog();
            String result = msg.getData().getString("result");
            if (result == null || result.equals("error")) {
                showAlertDialog(VPOSActivity.this, getResources().getString(R.string.deal_fail), getResources().getString(R.string.system_error), false, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        onAccountTab(null);
                        finish();
                    }
                });
            } else {
                int index1 = result.indexOf("<responseCode>") + "<responseCode>".length();
                int index2 = result.indexOf("</responseCode>");
                if (index1 >= 0 && index2 > index1) {
                    String responseCode = result.substring(index1, index2);
                    if (responseCode != null && responseCode.equals("00")) {
                        // 交易成功,通知商城
                        Intent intent = new Intent();
                        intent.setClass(VPOSActivity.this, ShowHtmlActivity.class);
                        intent.putExtra(ShowHtmlActivity.ShowHtml_Title_Key, getString(R.string.phone_charge));
                        intent.putExtra(ShowHtmlActivity.ShowHtml_Html_Path_Key, treatRespToWeb(responseCode));
                        startActivity(intent);
                        finish();
                    } else {
                        // 交易失败,弹出对话框显示
                        showAlertDialog(VPOSActivity.this, getResources().getString(R.string.deal_fail), "[" + responseCode + "]:" + Errors.getErrorString(responseCode), false, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                onAccountTab(null);
                            }
                        });
                    }
                }
            }
        }
    };

    public String treatRespToWeb(String responseCode) {
        try {
            StringBuffer sb = new StringBuffer();
            String[] code = {"RespCode", "RespDesc", "TransIndexCode", "TransAmount", "TransDate", "TransTime"};
            HashMap<String, String> respMap = new HashMap<String, String>();
            respMap.put("RespCode", responseCode);
            respMap.put("RespDesc", "");
            respMap.put("TransIndexCode", ShowHtmlActivity.map.get("orderId"));// 明文的orderId
            respMap.put("TransAmount", CommonUtils.formatMoenyToCurrency(ShowHtmlActivity.map.get("transAmount")));
            respMap.put("TransDate", ShowHtmlActivity.map.get("pSubTime").substring(0, 8));
            respMap.put("TransTime", ShowHtmlActivity.map.get("pSubTime").substring(8, 14));
            HPLog.e("fyang", "打印明文通知商城数据开始***********");
            for (String key : respMap.keySet()) {
                HPLog.e("key:" + key + "对应的value:", respMap.get(key));
            }
            HPLog.e("fyang", "打印明文通知商城数据结束***********");
            // 循环拼装通知的参数
            for (String s : code) {
                sb.append(s + "=" + WuXianDesUtil.encrypt(respMap.get(s) + "", "handpay2014!@#$%") + "&");
            }
            // 返回的是通知商城结果的请求地址
            // return "javascript:vposResNotify('" + sb.toString()+ "')";
            // return
            // "http://mps.handpay.cn/pgw/vposPaymentNotify.do?"+sb.toString();
            return "http://" + ZZTConfig.ENV.SERVER + "/pgw/vposPaymentNotify.do?" + sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}